<?php
/**
 * RedCross Application
 *
 * @copyright Copyright (c) 2010, Kristian Stokke Tryggestad, Rune Vikestad, Andreas Flaten Wist, Simen Nicolai Echholt, Ole Henrik Jahren
 */


class RedCross_View_Helper_NavigationMenu extends Zend_View_Helper_Abstract
{
    const USER_NAVIGATION = 'mainNavigation';
    const ADMIN_NAVIGATION = 'adminNavigation';

	public function navigationMenu()
	{
        return $this;
	}

	public function renderMenu($type = null, $name, $cache = false)
	{
	    if (!Zend_Registry::isRegistered($type)) {
	    	return;
	    }
	    $container = Zend_Registry::get($type);

	    if (count($container) === 0 || !$this->shouldRender($container)) {
	    	return;
	    }

        $this->view->addScriptPath(APPLICATION_PATH . '/layouts/main/menu/');

        if ($cache) {
        	$cacheResult = $this->_doCache($container, $type, $name);
        }
        return ($cache && $cacheResult) ? $cacheResult : $this->_render($container, $name);
	}

	private function _doCache($container, $type, $name)
	{
        if (!Zend_Registry::isRegistered('cacheManager')) {
            return false;
        }
        $log = Zend_Registry::get('log');

    	$manager = Zend_Registry::get('cacheManager');
    	if (!$manager->hasCache('navigationOutput')) {
    	    return false;
    	}
	    $log->info('Caching of navigation output is enabled for ' . $type . ': ' . $name);

		$cache = $manager->getCache('navigationOutput');

        $role = str_replace(':', '_', implode('_', $this->view->acl()->getParents()));
//		$role = str_replace(':', '_', $this->view->acl()->getRole()->getRoleId());
		$tag = $type . '_output_' . $role;
		if (!$content = $cache->load($tag)) {
		    $log->notice('Navigation cache for ' . $tag . ' was not found.. Creating a fresh cache');
			$content = $this->_render($container, $name);
		    $cache->save($content, null, array('navigation', 'navigationOutput', $role));
		}
		return $content;
	}

	private function _render($container, $name)
	{
    	$menu = $this->view->navigation()->menu();
        $menu->setPartial('menuCreator.phtml');
        return $this->view->partial('menu.phtml', array('title' => $name, 'menu' => $menu->renderPartial($container)));
	}

	private function shouldRender(Zend_Navigation_Container $container)
	{
	    $unAllowedPages = 0;
        foreach ($container as $page) {
        	if (!$this->view->navigation()->accept($page)) {
        		$unAllowedPages++;
        	}
        }
        return $unAllowedPages < count($container);
	}
}